﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.Resources;
using System.IO;
using System.Collections;
using System.Diagnostics;
using System.ComponentModel;
using TranslationAPI;

namespace ResourceTranslator
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        const string resourceFileFilter = "Resource Files (*.resx, *.resources)|*.resx;*.resources|Text Resource File (*.txt)|*.txt";
        const string resourceFileFilterFormat = "Resource Files (*.{0}.resx, *.{0}.resources)|*.{0}.resx;*.{0}.resources|Text Resource File (*.{0}.txt)|*.{0}.txt";

        string currentResourceFile;
        private void buttonBrowse_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = resourceFileFilter;
            openFileDialog.Multiselect = false;

            if (true == openFileDialog.ShowDialog())
            {
                txtResxFile.Text = openFileDialog.FileName;
                currentResourceFile = txtResxFile.Text;
                PopulateResourceValues(txtResxFile.Text);

                buttonTranslate.IsEnabled = true;


            }

            //PopulateResourceValues(txtResxFile.Text);
            //buttonTranslate.IsEnabled = true;
        }


        ResourceData[] currentResources;
        //IList<string> currentKeys;
        void PopulateResourceValues(string file)
        {
            originalResourcesViewer.LoadResourceFile(file);

            currentResources = originalResourcesViewer.ResourcesData;
        }

        delegate void MethodDelegate();

        string GetSelectedLanguage()
        {
            ComboBoxItem selectedItem = (ComboBoxItem)languagesComboBox.SelectedItem;
            string language = selectedItem.Tag as string;
            return language;
        }
        string GetSelectedSourceLanguage()
        {
            ComboBoxItem selectedItem = (ComboBoxItem)inputLanguagesComboBox.SelectedItem;
            string language = selectedItem.Tag as string;
            return language;
        }
        private void buttonTranslate_Click(object sender, RoutedEventArgs e)
        {
            BackgroundWorker worker = new BackgroundWorker();

            string sourcelanguage = GetSelectedSourceLanguage();
            string language = GetSelectedLanguage();

            //ResourceData[] currentResources = originalResourcesViewer.ResourcesData;
            string[] texts = new string[currentResources.Length];
            for (int i = 0; i < currentResources.Length; i++)
                texts[i] = currentResources[i].Value;

            worker.DoWork += new DoWorkEventHandler((obj, args) =>
                {
                    StartTranslation();
                    try
                    {
                        IEnumerable<string> translatedTexts = Translate(texts, sourcelanguage, language);
                        List<ResourceData> translatedResources = new List<ResourceData>(texts.Length);

                        int i = 0;
                        foreach (string translatedText in translatedTexts)
                        {
                            translatedResources.Add(
                                new ResourceData
                                {
                                    Key = currentResources[i].Key,
                                    Value = translatedText,
                                    Comments = currentResources[i].Comments
                                });
                            i++;
                        }

                        this.Dispatcher.BeginInvoke(new MethodDelegate(() =>
                            {
                                translatedResourcesViewer.ResourcesData = translatedResources.ToArray();
                                saveButton.IsEnabled = true;
                            }));
                    }
                    finally
                    {
                        DoneTranslation();
                    }
                });
            worker.RunWorkerAsync();
        }

        ITranslator translator = TranslatorFactory.GetTranslator("http://www.codeplex.com/resourcetranslator");
        IEnumerable<string> Translate(string[] texts, string inputlanguage, string outputlanguage)
        {
            /*
            ServiceReference1.TextTranslationServiceClient serviceClient = new ResourceTranslator.ServiceReference1.TextTranslationServiceClient();
            return serviceClient.TranslateBulk(texts, inputlanguage, outputlanguage);
            */
            return translator.Translate(texts, inputlanguage, outputlanguage);
        }

        void StartTranslation()
        {
            this.Dispatcher.BeginInvoke(new MethodDelegate(() =>
                {
                    translationProgressBar.Visibility = Visibility.Visible;
                    buttonTranslate.IsEnabled = false;
                    buttonTranslate.Content = "Translating...";
                }));
        }
        void DoneTranslation()
        {
            this.Dispatcher.BeginInvoke(new MethodDelegate(() =>
                {
                    translationProgressBar.Visibility = Visibility.Hidden;
                    buttonTranslate.IsEnabled = true;
                    buttonTranslate.Content = "Translate";
                }));
        }

        string GetResourceName(string resourceFile, out string locale)
        {
            string resourceFileNameWithoutExt = System.IO.Path.GetFileNameWithoutExtension(resourceFile);
            string culture = System.IO.Path.GetExtension(resourceFileNameWithoutExt);
            culture = culture.Replace(".", "");
            if (culture == String.Empty)
            {
                locale = "";
                return resourceFileNameWithoutExt;
            }
            locale = null;
            try
            {
                
                System.Globalization.CultureInfo.GetCultureInfo(culture);
                locale = culture;
                return System.IO.Path.GetFileNameWithoutExtension(resourceFileNameWithoutExt);
            }
            catch (ArgumentException)
            {
                locale = "";
                return resourceFileNameWithoutExt;
            }
        }
        private void saveButton_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = resourceFileFilter;
            string sourceLocale;
            saveFileDialog.FileName = GetResourceName(currentResourceFile, out sourceLocale)+"."+GetSelectedLanguage();
            if (saveFileDialog.ShowDialog() == true)
            {
                translatedResourcesViewer.SaveResourceFile(saveFileDialog.FileName);
            }
        }

        private void createSatelliteAsmButton_Click(object sender, RoutedEventArgs e)
        {
            SatelliteCreationWindow satelliteCreationWin = new SatelliteCreationWindow();
            satelliteCreationWin.ShowDialog();
            return;
            /*
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "Pick Resource Files";
            ofd.Filter = "*.resources|*.resources";
            ofd.Multiselect = true;

            if (ofd.ShowDialog() == true)
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "*.dll|*.dll";
                sfd.InitialDirectory = System.IO.Path.GetDirectoryName(ofd.FileName);

                sfd.DefaultExt = "*.dll";
                sfd.AddExtension = true;
                sfd.OverwritePrompt = true;

                if (sfd.ShowDialog() == true)
                {
                    SatelliteAssemblyUtil.CreateAssembly(sfd.FileName, ofd.FileNames, "hi", null);
                }
            }
             */
        }
    }
}
